// Copyright 2018 The Go Authors. All rights reserved.
// Use of this session code is governed by a BSD-style
// license that can be found in the LICENSE file.

package lsp

import (
	"context"
	"mi/internal/lsp/protocol"
	"mi/internal/lsp/session"
	"mi/internal/xpath"
)

func (s *Server) signatureHelp(ctx context.Context, params *protocol.SignatureHelpParams) (*protocol.SignatureHelp, error) {
	data, err := s.session.GetSignatureHelpItems(ctx, xpath.URI(params.TextDocument.URI), toUTF16Position(params.Position))
	if err != nil {
		return nil, err
	}
	if data == nil {
		return nil, nil
	}

	return toProtocolSignatureHelp(data), nil
}

func toProtocolSignatureHelp(data *session.SignatureHelpItems) *protocol.SignatureHelp {
	return &protocol.SignatureHelp{
		Signatures:      toProtocolSignatureInformations(data.Items),
		ActiveSignature: float64(data.SelectedItemIndex),
		ActiveParameter: float64(data.ArgumentIndex),
	}
}

func toProtocolSignatureInformation (item session.SignatureInformation) protocol.SignatureInformation {
	return protocol.SignatureInformation{
		Label:           item.Label,
		Documentation:   "",
		Parameters:      toProtocolParameters(item.Parameters),
		ActiveParameter: float64(item.ActiveParameter),
	}
}

func toProtocolSignatureInformations(items []session.SignatureInformation) []protocol.SignatureInformation {
	var result []protocol.SignatureInformation
	for _, item := range items {
		result = append(result, toProtocolSignatureInformation(item))
	}
	return result
}

func toProtocolParameter(param session.ParameterInformation) protocol.ParameterInformation {
	return protocol.ParameterInformation{
		Label:         param.Label,
		Documentation: param.Documentation,
	}
}

func toProtocolParameters(params []session.ParameterInformation) []protocol.ParameterInformation {
	var result []protocol.ParameterInformation
	for _, param := range params {
		result = append(result, toProtocolParameter(param))
	}
	return result
}